import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

const isWhiteList = (path) => {
  return whiteList.includes(path)
}

router.beforeEach((to, from, next) => {
  NProgress.start()

  // 在免登录白名单，直接进入
  if (isWhiteList(to.path)) {
    // 在免登录白名单，直接进入
    next()
    return
  }

  // 没有token全部重定向到登录页
  if (!getToken()) {
    next(`/login?redirect=${encodeURI(to.fullPath)}`)
    NProgress.done()
    return
  }

  /* has token*/

  if (to.meta.title) {
    document.title = to.meta.title
  }

  if (to.path === '/login') {
    next({ path: '/' })
    NProgress.done()
    return
  }

  // 已获取用户信息
  if (useUserStore().roles.length !== 0) {
    next()
    return
  }

  if (useUserStore().roles.length === 0) {
    // 判断当前用户是否已拉取完user_info信息
    useUserStore()
      .getInfo()
      .then(() => {
        next({ ...to, replace: true })
      })
      .catch((err) => {
        useUserStore()
          .logOut()
          .then(() => {
            next({ path: '/' })
          })
      })
  }
})

router.afterEach(() => {
  NProgress.done()
})
